package com.ruoyi.flowable.services;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.flowable.entity.UserTasksEntity;
import com.ruoyi.flowable.util.FlowSelectUtils;
import com.ruoyi.flowable.util.FlowUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysConfigService;
import org.flowable.bpmn.model.*;
import org.flowable.bpmn.model.Process;
import org.flowable.common.engine.impl.identity.Authentication;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/*
 * dustball  2021-04-11
 *
 * 业务逻辑处理
 */

@Service
public class ProcessEngineService {

    @Autowired
    protected RepositoryService repositoryService;

    @Autowired
    protected RuntimeService runtimeService;

    @Autowired
    protected TaskService taskService;

    @Autowired
    private TokenService tokenService;

    //提交流程
    public String postSubmit(String processDefinitionKey, String taskId, Map<String, Object> map, String currentUser) {

        String processInstanceId="";

        if (taskId == null || "".equals(taskId)) {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey).latestVersion().singleResult();
            BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());

            Process mainProcess = bpmnModel.getMainProcess();
            Collection<FlowElement> flowElements = mainProcess.getFlowElements();
            FlowElement firstUserTask = FlowSelectUtils.getFirstUserTask(flowElements);
            //启动流程
            Authentication.setAuthenticatedUserId(currentUser);
            Map<String, Object> startMap = new HashMap<>();
            startMap.put(firstUserTask.getId()+"_assignees", currentUser);
            ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinitionKey, startMap);
//            taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId())
            Task task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
            taskId = task.getId();
            processInstanceId=processInstance.getProcessInstanceId();
        }
        taskService.complete(taskId, map);

        return processInstanceId;

    }

    //获取下一步
    public List<UserTask> preSubmit(String id, Map<String, Object> map) {
        return FlowUtils.getNextUserTasks(repositoryService, taskService, taskService.createTaskQuery().taskId(id).singleResult(), map);

    }

    //获取下一步带路由
    public Map<String, List<UserTask>> preSubmitForRouter(String processId, String id, Map<String, Object> map) {
        if (id == null || "".equals(id) || "null".equals(id)) {
            return FlowSelectUtils.getNextUserTasks(repositoryService, taskService, processId, map);
        } else {
            return FlowSelectUtils.getNextUserTasks(repositoryService, taskService, taskService.createTaskQuery().taskId(id).singleResult(), map);
        }

    }


    //获取待办


    //获取已办


    //获取待阅


    //获取已阅


    /**
     * 获取节点的扩展参数
     * @param taskId
     * @return
     */

    public List<CustomProperty> getCurrentCustomPropsByTaskId(String taskId){
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionId(task.getProcessDefinitionId()).singleResult();
        BpmnModel bpmnModel = repositoryService.getBpmnModel(processDefinition.getId());
        String key = task.getTaskDefinitionKey();
        System.out.println(key);
        //UserTask userTask  = (UserTask) bpmnModel.getFlowElement(key);
        FlowElement flowElement = bpmnModel.getFlowElement(key);
        System.out.println(flowElement.getId());
        System.out.println(flowElement.getName());
        System.out.println(flowElement.getDocumentation());
        System.out.println(flowElement.getExecutionListeners().size());
        System.out.println(flowElement.getAttributes());
        //获取扩展属性
        Map<String, List<ExtensionAttribute>> attributes = flowElement.getAttributes();

        System.out.println(attributes.size());
        for(String keys:attributes.keySet()){
            System.out.println("keys:"+keys+" "+"Value:"+attributes.get(keys));
        }

//        //获取扩展属性
//        List<CustomProperty> customProps=userTask.getCustomProperties();
//        System.out.println(customProps.size());
//        for(CustomProperty customProperty:customProps){
//            //开始判断属性
//            System.out.println("----------------");
//            System.out.println(customProps);
//        }
        return null;
    }
}
